package ContentManagers.Servlets;

import ContentManagers.RoleManagers.AdminSessionManager;
import ContentManagers.Security.WebLogger;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Code sample showing how to perform a complete logout
 */
@SuppressWarnings("serial")
@WebServlet("/Logout")
public class ServletAdminLogout extends HttpServlet {

	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/*
		 * First step : Invalidate user session
		 */
                             
                HttpSession session = request.getSession();
                 WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Deauthentication of "+session.getAttribute("username")+" successful.",true); 
                 
                if (session != null) {
                    boolean sessionRelease = false;
                    
                    try{ //try first because an exception will be thrown when the session 
                         //has timed out after 5 minutes of no activity
                        sessionRelease = new AdminSessionManager().deleteAdminSession(session.getAttribute("username").toString());
                        } catch(Exception e){ /*do nothing*/ }
                    
                    session = request.getSession(false);
                    session.invalidate();
		}


		Cookie[] cookies = request.getCookies();
		if (cookies != null && cookies.length > 0) {
			for (Cookie cookie : cookies) {
				cookie.setValue("-");
				cookie.setMaxAge(0);
				response.addCookie(cookie);
			}
		}
                
                
                response.sendRedirect("index.jsp");
	}
    
}